# coding=utf-8
import json
from abc import ABCMeta

import tornado.web

import WrapCursor
from CommonLib import CheckJsonKeys, CheckAuth
from database.models.DatabaseCommon import *
from database.models.TimingSwitch import TimingSwitch

engine = create_engine('sqlite:///ai-ele.db?check_same_thread=False', echo=False)
Session = sessionmaker(bind=engine)
class SetTimingSwitch(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        print(self.request.path)
        ojson = None
        r = WrapCursor.WrapCursor()
        TimeID = None
        TimeEnable = None
        try:
            ojson = json.loads(self.request.body)
            TimeID = ojson['id']
            TimeEnable = ojson['enable']
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error('request data error :' + str(e)))
            return
        if not (TimeEnable == 0 or TimeEnable == 1):
            self.write(r.Error('request data error'))
            return
        if TimeID == "*":
            self.write(r.Error('warning : you are attack server'))
            return

        s = Session()
        tms = s.query(TimingSwitch).filter_by(id=TimeID).all()
        if len(tms) is 0:
            self.write(r.Error(u'错误:没有对应id的定时模式'))
            return
        tms[0].enable = TimeEnable

        try:
            s.commit()
        except Exception as e:
            self.write(r.Error(u'错误:数据库修改错误'))
            return
        self.write(r.Ok(u'成功'))
        return
